package com.lagou.eduorderboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lagou.eduorderboot.entity.PayOrder;
import com.lagou.eduorderboot.entity.PayOrderRecord;
import com.lagou.eduorderboot.entity.UserCourseOrder;
import com.lagou.eduorderboot.mapper.OrderDao;
import com.lagou.eduorderboot.mapper.PayOrderDao;
import com.lagou.eduorderboot.mapper.PayOrderRecordDao;
import com.lagou.eduorderboot.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private PayOrderDao payOrderDao;
    @Autowired
    private PayOrderRecordDao payOrderRecordDao;

    /**
     * 保存订单
     * @param orderNo 订单编号
     * @param user_id 用户编号
     * @param course_id 课程编号
     * @param activity_course_id 活动课程编号
     * @param source_type 订单来源类型
     */
    @Override
    public void saveOrder(String orderNo, String user_id, String course_id, String activity_course_id, String source_type) {
        UserCourseOrder order = new UserCourseOrder();
        order.setOrderNo(orderNo);
        order.setUserId(user_id);
        order.setCourseId(course_id);
        order.setActivityCourseId(Integer.parseInt(activity_course_id));
        order.setSourceType(source_type);
        order.setStatus(0);
        order.setIsDel(0);
        order.setCreateTime(new Date() );
        order.setUpdateTime(new Date() );

        orderDao.insert(order);
    }

    /**
     * 更新订单状态
     * @param orderNo 订单编号
     * @param status 订单状态 0已创建 10已支付 20已完成 30已取消 40已过期
     * @return
     */
    @Override
    public Integer updateOrder(String orderNo, int status) {
        UserCourseOrder order = new UserCourseOrder();
        order.setStatus(status);

        QueryWrapper q = new QueryWrapper();
        q.eq("order_no", orderNo);

        return orderDao.update(order,q);
    }

    /**
     * 删除订单
     * @param orderNo 订单编号
     * @return
     */
    @Override
    public Integer deleteOrder(String orderNo) {
        QueryWrapper q = new QueryWrapper();
        q.eq("order_no", orderNo);

        return orderDao.delete(q);
    }


    /**
     * 查询某个用户的全部订单
     * @param userId 用户编号
     * @return
     */
    @Override
    public List<UserCourseOrder> getOKOrderCourseIds(Integer userId) {
        QueryWrapper q = new QueryWrapper();
        q.eq("status", 20); //购买成功
        q.eq("is_del", Boolean.FALSE); // 未删除
        q.eq("user_id", userId); // 该用户
        return orderDao.selectList(q);
    }

    @Override
    public void saveOrderInfo(PayOrder payOrder) {
        payOrderDao.insert(payOrder);
    }

    @Override
    public void saveOrderRecord(PayOrderRecord payOrderRecord) {
        payOrderRecordDao.insert(payOrderRecord);
    }
}
